#include <iostream>
#include <memory>

class Test {
public:
    Test() { std::cout << "Test::Test()" << std::endl; }
    ~Test() { std::cout << "Test::~Test()" << std::endl; }
};


struct Bad
{
    std::shared_ptr<Bad> getptr()
    {
        return std::shared_ptr<Bad>(this);
    }
    ~Bad() { std::cout << "Bad::~Bad() called\n"; }
};

void testBad()
{
    // Bad, each shared_ptr thinks it's the only owner of the object
    std::shared_ptr<Bad> bad0 = std::make_shared<Bad>();
    std::shared_ptr<Bad> bad1 = bad0->getptr();
    std::cout << "bad1.use_count() = " << bad1.use_count() << '\n';
} // UB: double-delete of Bad


class Good : public std::enable_shared_from_this<Good>
{
public:
    std::shared_ptr<Good> getptr()
    {
        return shared_from_this();
    }
};

void testGood()
{
    // Good: the two shared_ptr's share the same object
    std::shared_ptr<Good> good0 = std::make_shared<Good>();
    std::shared_ptr<Good> good1 = good0->getptr();
    std::cout << "good1.use_count() = " << good1.use_count() << '\n';
}

void misuseGood()
{
    // Bad: shared_from_this is called without having std::shared_ptr owning the caller
    try
    {
        Good not_so_good;
        std::shared_ptr<Good> gp1 = not_so_good.getptr();
    }
    catch (std::bad_weak_ptr& e)
    {
        // undefined behavior (until C++17) and std::bad_weak_ptr thrown (since C++17)
        std::cout << e.what() << '\n';
    }
}

void alsoGood()
{
    // also good
    try
    {
        Good* also_good = new Good();
        std::shared_ptr<Good> gp(also_good);
        std::shared_ptr<Good> gp1 = also_good->getptr();
    }
    catch (std::bad_weak_ptr& e)
    {
        // undefined behavior (until C++17) and std::bad_weak_ptr thrown (since C++17)
        std::cout << e.what() << '\n';
    }
}

class Best : public std::enable_shared_from_this<Best>
{
public:
    std::shared_ptr<Best> getptr()
    {
        return shared_from_this();
    }
    // No public constructor, only a factory function,
    // so there's no way to have getptr return nullptr.
    [[nodiscard]] static std::shared_ptr<Best> create()
    {
        // Not using std::make_shared<Best> because the c'tor is private.
        return std::shared_ptr<Best>(new Best());
    }
private:
    Best() = default;
};
 

int main() {
    {
        // Test* t = new Test();
        // std::shared_ptr<Test> p1(t);
        // std::shared_ptr<Test> p2(t);

        std::shared_ptr<Test> p1(new Test);
        std::shared_ptr<Test> p2(p1);
    }

    {
        auto p1 = std::make_shared<Test>();
        auto p2 = p1;
    }

    {
        misuseGood();
    }

    return 0;
}